/*
 * @author : Amissah Gideon<kuulmek@yahoo.com>
 */
var Credit = {
    ssUrl:'CreditControl/add',
    selected_row_id:null,

    /* dataTable Object */
    objGrid:null,

    /* Function init
     * @param void
     * @return void
     * @access public
     * */
    init:function () {
        var self = this;

        /*Sortable Table */
        var oTable = null;
        var dataUrl = $('#table-url').val();

        self.objGrid = $('#flex').flexigrid({
            url:dataUrl,
            dataType:'json',
            colModel:[
                {display:'ID', name:'id', width:20, sortable:false, align:'left', hide:true},
                {display:'Purchased Date', name:'purchased_date', width:90, sortable:true, align:'center', hide:false},
                {display:'Customer', name:'customer_id', width:170, sortable:true, align:'center', hide:false},
                {display:'Sales No.', name:'vehicle_no', width:100, sortable:true, align:'center', hide:false},
                 //{display:'Duration', name:'end_date', width:85, sortable:true, align:'center', hide:false},
                //{display: 'Duration in Month', name : 'dm', width : 100, sortable : false, align: 'center', hide:false},
                //{display: 'Items Purchased', name : 'ip', width : 100, sortable : false, align: 'center', hide:false},
                //{display:'Principal GHc', name:'cost', width:60, sortable:false, align:'center', hide:false},
                //{display:'Interest Amount', name:'deposit', width:100, sortable:false, align:'center', hide:false},
                {display:'Opening Balance', name:'open_bal', width:110, sortable:false, align:'center', hide:false},
                {display:'Installment', name:'installment', width:80, sortable:false, align:'center', hide:false},
                {display:'Total Repayment', name : 'total_installment', width : 100, sortable : false, align: 'center', hide:false},
                {display:'Principal Balance', name:'balance', width:100, sortable:false, align:'center', hide:false},
                {display:'Total Interest', name : 'total_interest', width : 100, sortable : false, align: 'center', hide:false},
                {display:'Total Balance', name:'total_balance', width:100, sortable:false, align:'center', hide:false}
                //{display: 'Last Month Paid ', name : 'lmp', width : 100, sortable : false, align: 'center', hide:false},
                //{display: 'Next Credit Date', name : 'ncd', width : 100, sortable : false, align: 'center', hide:false},
                //{display: 'Comment', name : 'comments', width : 100, sortable : false, align: 'center', hide:false}
            ],
            formFields:[
                /*{type:'buttom',name: 'Add', bclass: 'add', onpress : Credit.handleGridEvent},
                 {separator: true},
                 {type:'buttom',name: 'Edit / View', bclass: 'edit', onpress : Credit.handleGridEvent},
                 {separator: true},
                 {type:'buttom',name: 'Delete', bclass: 'delete', onpress : Credit.handleGridEvent},
                 {separator: true},*/
                {type:'buttom', name:'More Detail', bclass:'view', onpress:self.handleGridEvent},
                {separator:true},
                {type:'buttom', name:'Client Statement', bclass:'repayment', onpress:self.handleGridEvent},
                {separator:true},
                {type:'buttom', name:'Client Amortization', bclass:'amortize', onpress:self.handleGridEvent},
                {separator:true},
                {type:'select', name:'Select Cutomers', id:'select_customer' ,bclass:'person', options:gbl_customers_sales , onchange:self.handleGridEvent}
            ],
            /*searchitems : [
             {display: 'Name', name : 'name', isdefault: true}
             ],*/
            checkboxSelection:true,
            columnControl:true,
            sortname:"id",
            sortorder:"desc",
            usepager:true,
            useRp:true,
            rp:15,
            showTableToggleBtn:false,
            height:300,
            onSubmit: self.addFormData
        });

        /** Credit Section **/

        $('#credit-save-btn').click(function () {
            self.saveCustomerCredit();
        });

        $('#credit-close-btn').click(function () {
            $.colorbox.close();
            self.selected_row_id = null;
        });

        $("#credit-form").validationEngine();


        /** Update the total cost if there is a change in quantity **/
        $('#credit-form-window #credit-form #quantity').focusout(function () {
            var value = parseFloat($(this).val());
            var old_amt = parseFloat($('#credit-form-window #credit-form #cost').val());
            if (value == 0) {
                value = 1;
                $(this).val(1);
            }
            var new_amt = old_amt * value;
            $('#credit-form-window #credit-form #cost').val(new_amt.toFixed(2));
        });

        /** On change on equipmemnt bought **/
        $('#credit-form-window #credit-form #equipment_id').change(function () {
            var id = $(this).val();
            var amount = parseFloat(global_equipment_data[id]['amount']);
            var quantity = parseFloat($('#credit-form-window #credit-form #quantity').val());
            var amt = amount * quantity;
            $('#credit-form-window #credit-form #cost').val(amt.toFixed(2));
        });

        self.initDataTypeMenus();
    },

    handleGridEvent:function (com, grid, json) {

        if (com == 'More Detail') {
            if (jLib.rowSelectedCheck(grid, 1)) {
                Credit.view(jLib.getSelectedRowIds(grid));
            }
        }
        else if (com == 'Client Statement') {
            if (jLib.rowSelectedCheck(grid, 1)) {
                Credit.repaymentDetails(jLib.getSelectedRowIds(grid));
            }
        }
        else if (com == 'Client Amortization') {
            if(jLib.rowSelectedCheck(grid,1)){
                Credit.amortization(jLib.getSelectedRowIds(grid));
            }
        }
        else if (com == 'Select Cutomers') {
            Credit.filterCustomers(json);
        }
    },

    filterCustomers:function(value){
        var self = this;
        self.objGrid.flexOptions({params: [{name:'customer_id',value:value}]}).flexReload();
        return false;
    },

    addFormData:function(){
        var self = this;
        var val = $("#select_customer").val();
        //self.objGrid.flexOptions({params: [{name:'customer_id',value:val}]});
        $('#creditflex').flexOptions({params: [{name:'customer_id',value:val}]});
        return true;
    },


    view:function (row_ids) {
        var self = this;

        var dataID = row_ids[0];
        var url = $('#load-user-url').val();
        var query = 'type=load&data-id=' + dataID;
        $.post(url, query, function (response) {
            if (response.code === 0) {
                var dataObj = response.data;
                var currency = dataObj['Sale']['currency'];
                $('#credit-form-window p span.officer_incharge').html(dataObj['Sale']['officer_incharge']);
                $('#credit-form-window p span.invoice_number').html(dataObj['Sale']['invoice_number']);
                $('#credit-form-window p span.name').html(dataObj['Customer']['name']);
                $('#credit-form-window p span.vehicle_no').html(dataObj['Sale']['vehicle_no']);
                $('#credit-form-window p span.purchased_date').html(dataObj['Sale']['purchased_date']);
                $('#credit-form-window p span.end_date').html(dataObj['Sale']['end_date']);
                $('#credit-form-window p span.duration_in_month').html(dataObj['Sale']['duration_in_month']);
                $('#credit-form-window p span.items').html(dataObj['Sale']['items']);
                $('#credit-form-window p span.cost').html(currency+" "+dataObj['Sale']['cost']);
                $('#credit-form-window p span.discount').html(currency+" "+dataObj['Sale']['discount']);
                $('#credit-form-window p span.deposit').html(currency+" "+dataObj['Sale']['deposit']);
                $('#credit-form-window p span.principal').html(currency+" "+dataObj['Sale']['principal']);
                $('#credit-form-window p span.interest').html(dataObj['Sale']['armotization']['interest_ratio']);
                $('#credit-form-window p span.total_interest').html(currency+" "+dataObj['Sale']['armotization']['tl_inerest']);
                $('#credit-form-window p span.installment').html(currency+" "+dataObj['Sale']['installment']);
                $('#credit-form-window p span.total_installment').html(currency+" "+dataObj['Sale']['total_installment']);
                $('#credit-form-window p span.balance').html(currency+" "+dataObj['Sale']['prin_balance']);
                $('#credit-form-window p span.tl_balance').html(currency+" "+dataObj['Sale']['total_balance']);
                $('#credit-form-window p span.last_paid_date').html(dataObj['Sale']['last_paid_date']);
                $('#credit-form-window p span.next_credit_date').html(dataObj['Sale']['next_credit_date']);
                $('#credit-form-window p span.comments').html(dataObj['Sale']['comments']);

                self.selected_row_id = dataID;

                $.colorbox({
                    inline:true,
                    scrolling:false,
                    overlayClose:false,
                    escKey:false,
                    title:'Credit Detail Information',
                    href:"#credit-form-window"
                });
            }
            /* When there are Errors */
            else if (response.code === 1) {
                /* Alert the user that the server response*/
                jLib.serverError(response.mesg);
            }
        }, 'json');
    },

    repaymentDetails:function (row_ids) {
        var self = this;

        var dataID = row_ids[0];

        self.selected_row_id = dataID;

        var url = $('#repayment-url').val();
        var query = 'data-id=' + dataID;
        $.post(url, query, function (response) {
            if (response.code === 0) {
                $('table#repayment_detail_flex tbody').html('');
                var dataObj = response.data;

                $('#repayment-window #transaction_currency').html(response.data['Sale']['currency']);

                $.each(response.data['Sale']['repayment'],function(index, row){
                    var tr = $("<tr />");
                    for(var x=0; x<row.length; x++){
                        tr.append($("<td />").html(row[x]));
                    }
                    $('table#repayment_detail_flex tbody').append(tr);
                });

                //$('#repayment_detail_flex').flexigrid({height:400});

                $.colorbox({
                    inline:true,
                    scrolling:false,
                    overlayClose:false,
                    escKey:false,
                    title:'Client Statement',
                    href:"#repayment-window",
                    height:550
                });

                /*$("table.thfloat").thfloat({
                    attachment : ".thflotDiv"
                });*/

            }
            /* When there are Errors */
            else if (response.code === 1) {
                /* Alert the user that the server response*/
                jLib.serverError(response.mesg);
            }
        }, 'json');
    },


    amortization:function (row_ids) {
        var self = this;

        var dataID = row_ids[0];

        self.selected_row_id = dataID;

        var url = $('#amortization-url').val();
        var query = 'data-id=' + dataID;
        $.post(url, query, function (response) {
            if (response.code === 0) {
                $('table#amortization_detail_flex tbody').html('');
                var dataObj = response.data;
                var cur = dataObj['currency'];
                var tl_pay = parseFloat(dataObj['opening_bal_raw']) + parseFloat(dataObj['tl_inerest_raw']);

                $("#amortization-window table tr td span#loan_amt").html(cur+" "+dataObj['opening_bal']);
                $("#amortization-window table tr td span#int_rate").html(dataObj['interest_ratio']);
                $("#amortization-window table tr td span#tl_period").html(dataObj['duration_in_month']);
                $("#amortization-window table tr td span#pay_per_period").html(cur+" "+dataObj['monthly_inst']);
                $("#amortization-window table tr td span#tl_int_paid").html(cur+" "+dataObj['tl_inerest']);
                $("#amortization-window table tr td span#tl_payment").html(cur+" "+jLib.formatNumber(tl_pay,'money'));


                $.each(dataObj['data'],function(index, row){
                    var tr = $("<tr />");
                    for(var key in row){
                        tr.append($("<td />").html(row[key]));
                    }

                    $('table#amortization_detail_flex tbody').append(tr);
                });

                //$('#amortization_detail_flex').flexigrid({height:400});

                $.colorbox({
                    inline:true,
                    scrolling:false,
                    overlayClose:false,
                    escKey:false,
                    title:'Client Amortization',
                    href:"#amortization-window",
                    height: 600
                });
            }
            /* When there are Errors */
            else if (response.code === 1) {
                /* Alert the user that the server response*/
                jLib.serverError(response.mesg);
            }
        }, 'json');
    },

    delete_:function (grid) {
        var self = this;

        var url = $('#delete-url').val();
        jLib.do_delete(url, grid);
    },

    initDataTypeMenus:function(){
        var self = this;

        $("button.data-type-menu").live('click',function(){
            var action = $(this).attr('action');
            var data_type = $(this).attr('data-type');
            var url = $("#"+action+"-url").val()+'/'+self.selected_row_id+'/'+data_type;

            window.open(url,action,"menubar=yes, width=600, height=500,location=no,status=no,scrollbars=yes,resizable=yes");
        });

    }
};

/* when the page is loaded */
$(document).ready(function () {
    Credit.init();
});